package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	nhttp "net/http"
	"wzgames/internal/admin/adc"
	"wzgames/internal/admin/adcomm"
	"wzgames/internal/admin/api/cp"
	"wzgames/internal/admin/api/mid"
	"wzgames/internal/admin/api/stm"
	"wzgames/internal/admin/api/sys"
	"wzgames/internal/admin/api/user"
	"wzgames/internal/admin/api/wzabind"
	"wzgames/internal/admin/model"
	"wzgames/internal/gvalidator"
	"wzgames/internal/response"
	"wzgames/pkg/server/http"
	"wzgames/pkg/server/http/types"
)

func initRouteGroups(group *gin.RouterGroup) {
	sys.RegisterRoute(group)
	cp.RegisterCachePushRoute(group)
	stm.RegisterRoute(group)
	user.RegisterUserRoute(group)
}

func InitRoute(g *gin.Engine) {
	rootGroup := g.Group("/")
	versionGroup := rootGroup.Group("wza")
	apiGroup := versionGroup.Group("api")
	apiGroup.Use(mid.WZAuth())
	initRouteGroups(apiGroup)
	http.MethodMapper(versionGroup, types.POST)(loginFn())
}

var loginFn = func() (string, func(c *gin.Context)) {
	uri := fmt.Sprintf("/login")
	return uri, func(c *gin.Context) {
		resp := model.Response{}
		clientToken := c.GetHeader(adcomm.ClientTokenKey)
		var params wzabind.SysLoginReq
		if err := c.ShouldBindJSON(&params); err != nil {
			//logger.Error("err == ", zap.String("error", err.Error()))
			resp.Code = response.ErrBadRequest
			c.JSON(nhttp.StatusOK, resp)
			return
		}
		if !gvalidator.IsAlphaNumeric(clientToken) || len(clientToken) > 32 {
			resp.Code = response.ErrBadRequest
			c.JSON(nhttp.StatusOK, resp)
			return
		}

		adm, code := adc.PP().CheckAccount(params)
		if code == 0 {
			token, c := adc.PP().GenAdminTicket(adm, clientToken)
			if c == 0 {
				resp.Data = map[string]string{adcomm.TokenKey: token}
			}
			code = c
		}
		resp.Code = code

		c.JSON(nhttp.StatusOK, resp)
		return
	}
}
